package user_v1

import (
	"context"
	"gf-xb-api/internal/consts"
	"gf-xb-api/utility/xredis"

	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/database/gredis"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

func (s *sUser) LogoutByUuid(ctx context.Context, uuid string) (err error) {
	allDeviceTypes := []consts.DeviceType{consts.PC, consts.Phone, consts.Pad, consts.MiniProgram}

	for _, deviceType := range allDeviceTypes {

		redisKey := xredis.JwtTokenKey(uuid, int(deviceType))
		redisVal, err := g.Redis().Get(ctx, redisKey)
		if err != nil {
			return err
		}

		if redisVal.Val() == nil {
			continue
		}

		// 删除redisKey
		_, err = g.Redis().Del(ctx, redisKey)
		if err != nil {
			return err
		}

		// 设置黑名单
		// md5
		token, err := gmd5.EncryptString(redisVal.String())
		if err != nil {
			return err
		}

		timeoutSeconds := g.Config().MustGet(ctx, consts.JWT_TIMEOUT).Int()
		maxRefresh := g.Config().MustGet(ctx, consts.JWT_MAXREFRESH).Int()

		var expiry *int64 = gconv.PtrInt64(timeoutSeconds)
		if timeoutSeconds < maxRefresh {
			expiry = gconv.PtrInt64(maxRefresh)
		}

		blackRedisKey := consts.JWT_TOKEN_BLACKLIST_REDISKEY + token
		_, err = g.Redis().Set(ctx, blackRedisKey, true, gredis.SetOption{
			TTLOption: gredis.TTLOption{
				EX: expiry,
			},
		})
		if err != nil {
			return err
		}
	}

	return
}
